package com.xzz.mybatis.generator.utils;

import com.google.common.collect.Lists;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 一些简单集合工具类
 */
public final class MyCollectionUtil {

    private MyCollectionUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 判断是否为空或空集合
     *
     * @param source
     */
    public static boolean isEmptyOrNull(Collection source) {
        return null == source || source.isEmpty();
    }

    /**
     * 判断是不为空集合
     *
     * @param source
     */
    public static boolean isNotEmptyOrNull(Collection source) {
        return null != source && !source.isEmpty();
    }

    public static <T> List<T> reduce(Collection<List<T>> list) {
        if (isEmptyOrNull(list)) {
            return Collections.emptyList();
        }
        return list.stream().reduce(Lists.newArrayList(), (c1, c2) -> {
            if (isEmptyOrNull(c2)) {
                return c1;
            }
            c1.addAll(c2);
            return c1;
        });
    }

    public static <T, E> List<E> reduce(Collection<T> collection, Function<T, List<E>> getMapper) {
        if (isEmptyOrNull(collection)) {
            return Collections.emptyList();
        }
        return reduce(collection.stream().map(getMapper).collect(Collectors.toList()));
    }

    public static <T, R> Set<R> mapToSet(Collection<T> collection, Function<T, R> getMapper) {
        if (isEmptyOrNull(collection)) {
            return Collections.emptySet();
        }
        return collection.stream().map(getMapper).collect(Collectors.toSet());
    }
}
